﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using OBiCMSFramework;

namespace OBiCMSUI
{
    class Utilities
    {
        // Public Methods
        public static DataSet GetDataset(String sql)
        {
            try
            {
                return StaticObjects.GetDataset(sql);
            }
            catch (Exception e)
            { }

            return new DataSet();
        }
        public static String UpdateDatabase(String sql)
        {
            try
            {
                StaticObjects.UpdateDatabase(sql);
                return "true";
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
        public static String ReplaceForDB(String stringToReplace)
        {
            return stringToReplace.Replace("'", "''");
        }
        public static String GenerateID(String typeInitials)
        {
            String Str_ID;
            String strLetters;
            Random ran = RandomFactory.Create();

            // Adds the Starting Letters and date to the ID
            Str_ID = typeInitials + DateTime.Now.ToUniversalTime().ToString("yyyyMMdd");

            // Creates a String of all the valid characters that can go at the end of the ID
            strLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

            // Calculates 6 random numbers and adds the letter onto the end of the ID
            Str_ID += ran.Next(100000, 999999).ToString() + strLetters.Substring(ran.Next(0, strLetters.Length), 1);

            return Str_ID;
        }
        public static String ReplaceAllowedCharacters(String stringToReplace)
        {
            return stringToReplace.Replace("[CMSLT]", "<");
        }
        public static String ReplaceForJSON(String stringToReplace)
        {
            return stringToReplace.Replace(Environment.NewLine, "[CMSNL]")
                                  .Replace("\"", "[CMSQ]")
                                  .Replace("'", "[CMSSQ]")
                                  .Replace("&", "[CMSAND]")
                                  .Replace("\\", "\\\\")
                                  .Replace("/", "\\/");
        }

        // Private Classes
        private static class RandomFactory
        {
            private static Random globalRandom = new Random();

            public static Random Create()
            {
                lock (globalRandom)
                {
                    Random newRandom = new Random(globalRandom.Next());
                    return newRandom;
                }
            }
        }
    }
}
